Page({
  data: {
    avatarUrl: '/images/setting/images.png', // 默认头像
    nickName: '未登录', // 默认昵称
    isLogin: false, // 登录状态
    tabIndex: 3,
    menuList: [
      { title: '宠物偏好', icon: '/images/setting/icon/dog.png' },
      { title: '个人资料', icon: '/images/setting/icon/user.png' },
      { title: '通知', icon: '/images/setting/icon/massage.png' },
      { title: '已领养', icon: '/images/setting/icon/safe.png' },
      { title: '帮助与支持', icon: '/images/setting/icon/help.png' }
    ],
    pagePaths: [
      "",  // 宠物偏好
      "/pages/setting-userinfo/setting-userinfo",  // 个人资料
      "/pages/setting-message/setting-message",  // 通知
      "/pages/setting-my-ppts/setting-my-ppts",  // 已领养
      "/pages/setting-help/setting-help"  // 帮助与支持
    ],
    petPreferences: [
      { label: "🐶 狗狗", value: "dog", selected: true },
      { label: "🐱 猫猫", value: "cat", selected: false },
      { label: "🐰 兔子", value: "rabbit", selected: false },
      { label: "🐦 鸟类", value: "bird", selected: false },
      { label: "🐹 仓鼠", value: "hamster", selected: false },
      { label: "🐢 乌龟", value: "turtle", selected: false },
      { label: "🦎 蜥蜴", value: "lizard", selected: false },
      { label: "🐍 蛇", value: "snake", selected: false },
      { label: "🦜 鹦鹉", value: "parrot", selected: false },
      { label: "🦔 刺猬", value: "hedgehog", selected: false },
      { label: "🐸 青蛙", value: "frog", selected: false },
      { label: "🦝 浣熊", value: "raccoon", selected: false },
      { label: "🦆 鸭子", value: "duck", selected: false },
      { label: "🐷 小猪", value: "pig", selected: false },
    ]
    ,
    showPetPrefModal: false
  },

  // 获取用户授权信息
  getMyInfo: function () {
    wx.getUserProfile({
      desc: '用于完善个人信息',
      success: res => {
        const { avatarUrl, nickName } = res.userInfo;
        wx.login({
          success: loginRes => {
            const code = loginRes.code;
            wx.request({
              url: 'http://localhost:3000/user/login',
              method: 'POST',
              data: { code, avatarUrl, nickName },
              success: (res) => {
                if (res.data.code === 200) {
                  const baseInfo = res.data.data;
  
                  // 登录成功后，再请求完整信息（含 pet_preference）
                  wx.request({
                    url: 'http://localhost:3000/user/profile',
                    method: 'GET',
                    data: { openid: baseInfo.openid },
                    success: (res2) => {
                      if (res2.data.code === 200) {
                        const userInfo = res2.data.data;
                        const selectedPrefs = userInfo.pet_preference || [];
  
                        const prefs = this.data.petPreferences.map(item => ({
                          ...item,
                          selected: selectedPrefs.includes(item.value)
                        }));
  
                        this.setData({
                          avatarUrl: userInfo.avatarUrl,
                          nickName: userInfo.nickName,
                          isLogin: true,
                          petPreferences: prefs
                        });
  
                        wx.setStorageSync('userInfo', userInfo);
                      }
                    }
                  });
                }
              }
            });
          }
        });
      }
    });
  }, 

  // 点击菜单跳转
  onMenuClick: function (e) {
    const index = e.currentTarget.dataset.index;
    if (index === 0) {
      // 宠物偏好，打开弹窗
      this.setData({ showPetPrefModal: true });
    } else {
      const path = this.data.pagePaths[index];
      wx.navigateTo({ url: path });
    }
  },
  togglePreference(e) {
    const index = e.currentTarget.dataset.index;
    const prefs = this.data.petPreferences;
    prefs[index].selected = !prefs[index].selected;
    this.setData({ petPreferences: prefs });
  },

  closeModal() {
    this.setData({ showPetPrefModal: false });
  },

  savePreference() {
    const selectedPrefs = this.data.petPreferences
      .filter(p => p.selected)
      .map(p => p.value); 
    console.log(selectedPrefs);
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.openid) {
      return wx.showToast({ title: '未登录', icon: 'none' });
    }
  
    wx.request({
      url: 'http://localhost:3000/user/profile',
      method: 'POST',
      data: {
        openid: userInfo.openid,
        pet_preference: selectedPrefs, 
        avatarUrl: userInfo.avatarUrl,
        fullName: userInfo.fullName || '',
        phone: userInfo.phone || '',
        address: userInfo.address || ''
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '保存成功', icon: 'success' });
          this.setData({ showPetPrefModal: false });
        } else {
          wx.showToast({ title: '保存失败', icon: 'none' });
        }
      }
    });
  },

  // 退出登录
  logout: function () {
    wx.showModal({
      title: '退出登录',
      content: '您确定要退出？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            avatarUrl: '/images/setting/images.png',
            nickName: '未登录',
            isLogin: false
          });
          wx.removeStorageSync('userInfo');
          wx.showToast({ title: '已退出登录', icon: 'success' });
        }
      }
    });
  },

  onShow() {
    const cached = wx.getStorageSync('userInfo');
    if (!cached || !cached.openid) {
      this.setData({
        avatarUrl: '/images/setting/images.png',
        nickName: '未登录',
        isLogin: false
      });
      return;
    }
  
    wx.request({
      url: 'http://localhost:3000/user/profile',
      method: 'GET',
      data: { openid: cached.openid },
      success: (res) => {
        if (res.data.code === 200) {
          const userInfo = res.data.data;
          const selectedPrefs = userInfo.pet_preference || [];
  
          const prefs = this.data.petPreferences.map(item => ({
            ...item,
            selected: selectedPrefs.includes(item.value)
          }));
          
          this.setData({
            avatarUrl: userInfo.avatarUrl,
            nickName: userInfo.nickName,
            isLogin: true,
            petPreferences: prefs
          });
  
          wx.setStorageSync('userInfo', userInfo); 
        } else {
          wx.showToast({ title: '加载失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  
    this.setData({ tabIndex: 3 });
  },

  // tab切换逻辑
  onTabChange(e) {
    const index = e.detail.index;
    const tabPages = [
      '/pages/index/index',
      '/pages/cart/cart',
      '/pages/map-pet/map-pet',
      '/pages/settings/settings'
    ];
    if (index === this.data.tabIndex) return;
    wx.switchTab({ url: tabPages[index] });
  }
});
